<!-- eslint-disable vue/html-closing-bracket-newline -->
<!-- eslint-disable vue/max-attributes-per-line -->
<template>
  <!-- 每个table表头的popover -->
  <!-- 注意：逻辑部分尽量不好写到这个组件内，因为这个组件是根据外面table循环创建的，在这里写逻辑会非常影响性能 -->
  <div
    class="customHeader"
    style="display: inline-block"
  >
    <el-popover
      :ref="`popover-${columnIndex}`"
      placement="bottom"
      trigger="click"
    >
      <!-- table表头文字显示-->

      <span
        slot="reference"
        class="name"
      >
        <div :class="{'header-filter-flag': filterForm.value !== undefined }"></div>
        <!-- <zn-icon :icon="column.extra.icon" /> -->
        {{ column.name }} &nbsp;
        <!-- 显示详情 可以优化 -->
        <span
          v-if="filterForm.value!== undefined && column.valueFormat !== 'timestamp'&&column.type !== 'TimePicker'&&column.type !== 'datetime_range'"
          class="filterVal"
          :title="(filterForm.name || filterForm.value) + ' 按住shift可以滚动'"
        >({{ filterForm.name || filterForm.value }})</span>
        <span
          v-else-if="filterForm.value!== undefined&&column.type === 'date'"
          class="filterVal"
          :title="dateToFormattwo(filterForm.value) + ' 按住shift可以滚动'"

        >
          ({{ dateToFormattwo(filterForm.value) }})
        </span>
        <span
          v-else-if="
            (filterForm.value!== undefined&&column.type === 'datetime')"
          style="color:red;"
          class="filterVal"
        >
          ({{ dateToFormat(filterForm.value) }})
        </span>
        <span
          v-else-if="(filterForm.value!== undefined&&column.type === 'TimePicker')||
            (filterForm.value!== undefined&&column.type === 'datetime_range')"
          style="color:red;"
          class="filterVal"
        >
          ({{ filterForm.value[0] }} - {{ filterForm.value[1] }})
        </span>
        <i class="el-icon-arrow-down"></i>
      </span>
      <!-- text 文本 -->
      <div v-if="column.type === 'input'">
        <el-input
          v-model.trim="filterForm.value"
          clearable
          placeholder="请输入查询内容"
          @keyup.native.enter="confirm()"
        />
      </div>
      <!-- number 数字框 -->
      <div v-else-if="column.type === 'number'">
        <el-input
          v-model.trim="filterForm.value"
          clearable
          oninput="value=value.replace(/[^0-9.]/g,'')"
          placeholder="请输入数字"
          @keyup.native.enter="confirm()"
        />
      </div>
      <!-- number_range 数字范围-->
      <div v-else-if="column.type === 'number_range'">
        <el-input
          v-model.trim="filterForm.value"
          style="width: 120px"
          clearable
          oninput="value=value.replace(/[^0-9.]/g,'')"
          placeholder="请输入数字"
        />-
        <el-input
          v-model.trim="spareValue"
          style="width: 120px"
          clearable
          oninput="value=value.replace(/[^0-9.]/g,'')"
          placeholder="请输入数字"
        />
      </div>
      <!-- date 单个日期-->
      <div v-else-if="column.type === 'date'">
        <el-date-picker
          v-model="filterForm.value"
          type="date"
          clearable
          placeholder="选择日期"
          :value-format="column.valueFormat || 'yyyy-MM-dd'"
        />
      </div>
      <!-- datetime 日期时间-->
      <div v-else-if="column.type === 'datetime'">
        <el-date-picker
          v-model="filterForm.value"
          type="datetime"
          placeholder="选择日期时间"
          :value-format="column.valueFormat || 'yyyy-MM-dd HH:mm:ss'"
        />
      </div>
      <!-- TimePicker 日期范围-->
      <div v-else-if="column.type === 'TimePicker'">
        <el-date-picker
          v-model="filterForm.value"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :value-format="column.valueFormat || 'yyyy-MM-dd'"
        />
      </div>
      <!-- datetime_range 日期时分秒范围-->
      <div v-else-if="column.type === 'datetime_range'">
        <el-date-picker
          v-model="filterForm.value"
          clearable
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :value-format="column.valueFormat || 'yyyy-MM-dd HH:mm:ss'"
        />
      </div>
      <!-- select 下拉选择-->
      <div v-else-if="column.type === 'Select'">
        <el-select
          v-model="filterForm.value"
          placeholder="请选择"
          style="width: 100%"
          filterable
          clearable
          @change="getValue"
        >
          <el-option
            v-for="(item, index) in filterOptions"
            :key="index"
            :name="item[filterName[0]] || item.name"
            :label="item[filterName[0]] || item.name"
            :value="item[filterName[1]] || item.value"
          />
        </el-select>
      </div>

      <!-- cascader 下拉选择-->
      <div v-else-if="column.type === 'cascader'">
        <el-cascader
          v-model="filterForm.value"
          placeholder="请选择"
          style="width: 100%"
          :options="filterOptions"
          :props="{
            expandTrigger: 'hover',
            label: filterName[0] || 'name',
            value: filterName[1] || 'value',
            children: filterName[2] || 'children',
            emitPath: false
          }"
        />
      </div>
      <!-- radio 单选-->
      <div v-else-if="column.type === 'radio'">
        <el-radio-group v-model="filterForm.value">
          <el-radio
            v-for="(item, index) in filterOptions"
            :key="index"
            :name="item.value"
            :value="item.value"
          >{{ item.name }}</el-radio>
        </el-radio-group>
      </div>
      <!-- checkBox 多选-->
      <div v-else-if="column.type === 'checkBox'">
        <el-checkbox-group v-model="checkboxList">
          <el-checkbox
            v-for="(item, index) in filterOptions"
            :key="index"
            :name="item.value"
            :value="item.value"
          >{{ item.name }}</el-checkbox>
        </el-checkbox-group>
      </div>

      <!-- confirm 确定框-->
      <div style="text-align: left">
        <el-button
          type="text"
          size="mini"
          class="confirm"
          @click="confirm()"
        >筛选</el-button>
        <el-button
          type="text"
          size="mini"
          class="confirm"
          @click="Reset(1)"
        >重置</el-button>

        <el-button
          type="text"
          size="mini"
          class="confirm"
          @click="Reset(2)"
        >全部重置</el-button>
      </div>
    </el-popover>
  </div>
</template>
<script>
// import { dateToFormat, dateToFormattwo } from "@/utils/validate";
import { livestockInverts } from '@/utils/index'

export default {
  name: "TypePopover",
  // column 当前列数据，filterOptions 多选/单选/下拉/数据
  props: {
    column: {
      type: Object,
      default: () => {}
    },
    filterOptions: {
      type: Array,
      default: () => []
    },
    filterName: {
      type: Array,
      default: () => []
    },
    columnIndex: {
      type: Number,
      default: 0
    },
    tableUpStauts: {
      type: Number,
      default: 1
    }
    // filterOptionsStauts: {
    //   type: Boolean,
    //   default: false
    // }
    // searchObj: {
    //   type: Object,
    //   default: () => {}
    // }
  },
  data() {
    return {
      filterForm: {
        tagname: this.column.name, // 筛选tag name(tag用)
        name: "", // 显示的
        tagValue: "", // 筛选tag value(tag用)
        value: undefined, // 所筛选的数据(后端接收用)
        fieldName: this.column.name, // 当前表头字段(后端接收用)
        porps: this.column.porps // 判断公母
      },
      spareValue: "", // 备用Value popover里如是两个值的话需要用此来拼接
      checkboxList: [],
      filterOptionsStauts: 1
    };
  },
  watch: {
    tableUpStauts: {
      deep: true,
      handler(val) {
        console.log(val);
        this.filterForm.value = undefined;
      }
    },
    filterOptions: {
    //   deep: true,
      handler(val) {
        // console.log(this.filterOptionsStauts, this.filterForm.value)
        if (!this.filterForm.value) return false;
        let i = true; // 声明一个变量，用做判断
        // 解决存储介质数组无对应匹配选问题，匹配不成功选择框显示为空
        try { // 因为要终止forEach循环，所以使用try、catch
          val.forEach(item => {
            if ((item[this.filterName[1]] || item.value) === this.filterForm.value) {
              throw new Error("匹配成功");
              // 匹配成功，抛出错误，进入catch事件;如果匹配不成功,就代表选择框的options与选择框value不匹配，不做任何操作，操持i的状态
            }
          });
        } catch (e) {
          i = false;
          this.filterOptionsStauts = 2;
          // 改变i的状态，使之不能进入把选择框值置为空条件
        }
        // i为true，value值与options匹配不成功，把value值置为null
        if (i) {
          this.filterForm.value = undefined;
          // console.log(this.filterOptionsStauts, this.confirm.name)
          // if (this.filterOptionsStauts === 1) {
          //   this.filterOptionsStauts = 2;
          this.Reset(1);
          // }
        }
        // }
      }
    }
  },
  created() {},
  methods: {
    getValue(e) {
      this.$emit("getSelectValue", e);
      // console.log(e);
      const index = this.filterOptions.findIndex(
        item => item[this.filterName[1] || "value"] === e
      );
      if (index !== -1) {
        this.$set(
          this.filterForm,
          "name",
          this.filterOptions[index][this.filterName[0] || "name"]
        );
      }
    },
    confirm() {
      let minValue = this.filterForm.value; // 数值双向绑定  做个闭环赋值
      let type = this.column.type;
      // 跟后端商定 , 多个值存在时进行判断 , 以filterForm.value一个值为字符串的形式传递
      // 根据需求做了处理
      // checkBox和radio和select由于value值的原因需要处理
      if (
        type === "checkBox" ||
        type === "radio" ||
        type === "select" ||
        type === "cascader"
      ) {
        if (type === "checkBox") {
          this.filterForm.value = this.checkboxList.join(",");
        }
        if (this.column.param && this.column.param.length > 0) {
          let str = "";
          this.column.param.forEach((i, t) => {
            if (
              type === "checkBox" &&
              i.value === Number(this.checkboxList[t])
            ) {
              str = str + i.name;
            }
            if (type === "radio" && i.value === Number(this.filterForm.value)) {
              str = str + i.name;
            }
            if (
              type === "select" &&
              i.value === Number(this.filterForm.value)
            ) {
              str = str + i.name;
            }
            if (
              type === "cascader" &&
              i.value === Number(this.filterForm.value)
            ) {
              str = str + i.name;
            }
          });
          this.filterForm.tagValue = str;
        } // 数字范围
      } else if (type === "number_range") {
        this.filterForm.tagValue =
          this.filterForm.value + " - " + this.spareValue;
        this.filterForm.value = this.filterForm.value + "," + this.spareValue;
      } else if (this.filterForm.value === "" && !this.spareValue) {
        return this.$message.warning("请输入或选择筛选条件");
      } else {
        this.filterForm.tagValue = this.filterForm.value; // 其他类型的赋值给tag用
      }
      if (this.column.porp.indexOf(".") !== -1) {
        this.filterForm.porp = this.column.porp.match(/\.(.*)/)[1];
        // this.filterForm.porps = this.column.porp.match(/(\S*)\./)[1];
        // if (typeof this.searchObj[this.filterForm.porps] === "object") {
        //   this.filterForm.types = "Object";
        // }
      } else {
        this.filterForm.porp = this.column.porp;
      }
      if (this.column.selectValue) {
        this.filterForm.selectValue = this.column.selectValue;
      }

      this.$emit("tableUpdate", {
        ...this.column,
        ...this.filterForm,
        columnType: this.column.type,
        value: livestockInverts(this.filterForm?.value),
        tagValue: livestockInverts(this.filterForm?.tagValue)
      }); // 传递的是对象
      this.filterForm.value = minValue; // 数值双向绑定  做个闭环赋值 ,俗称瞒天过海
      this.$refs["popover-" + this.columnIndex].doClose(); // 关闭popover
      this.filterOptionsStauts = 1;
    },
    Reset(e) {
      if (e === 1) {
        this.filterForm.tagValue = "";
        // this.filterForm.value = "";
        this.$set(this.filterForm, "value", undefined);
        this.$set(this.filterForm, "name", undefined);
        this.$emit("tableUpdate", {
          ...this.column,
          type: "Reset",
          columnType: this.column.type
        }); // 传递的是对象
      } else if (e === 2) {
        this.$emit("tableUpdate", {
          ...this.column,
          type: "wholeReset",
          columnType: this.column.type
        }); // 传递的是对象
      }
    }
  }
};
</script>
<style scoped>
.customHeader {
width: 100%;
display: flex;
justify-content: center;
align-items: center;
}
.confirm {
  margin-top: 10px;
}
/* 禁止双击选中文字 */
.name {
  -moz-user-select: none; /*火狐*/
  -webkit-user-select: none !important; /*webkit浏览器*/
  -ms-user-select: none; /*IE10*/
  -khtml-user-select: none; /*早期浏览器*/
  user-select: none;
  white-space: nowrap;
  display: flex;
  align-items: center;
  justify-content: center;
  /* max-width: 200px; */
  /* text-emphasis: ; */
  /* text-overflow: ellipsis; */
}
.name > div {
  position: absolute;
}
.filterVal {
  display: inline-block;
  white-space: nowrap;
  max-width: 120px;
  overflow: auto;
  color: red;
}
.filterVal::-webkit-scrollbar {
  width: 0px;
  height: 0px;
  padding: 0px 0;
}
.nameColor {
  color: #409eff;
}
.el-icon-arrow-down {
  cursor: pointer;
}

.el-checkbox-group {
  display: flex;
  justify-content: flex-start;
  flex-direction: column;
  max-height: 150px;
  overflow-y: auto;
}
.header-filter-flag {
  width: 0;
  height: 0;
  border-top: 6px solid red;
  border-right: 6px solid transparent;
  position: absolute;
  top: 0;
  left: 5px;
}
</style>
